package com.zs.usc.configuration.common;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;



@Configuration
public class RestTemplateConfiguration {

    private static Logger logger = LoggerFactory.getLogger(RestTemplateConfiguration.class);


//    @Bean
//    @ConditionalOnMissingBean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
//        PoolingHttpClientConnectionManager pollingConnectionManager = new PoolingHttpClientConnectionManager();
//        // 总连接数
//        pollingConnectionManager.setMaxTotal(1000);
//        // 同路由的并发数
//        pollingConnectionManager.setDefaultMaxPerRoute(1000);
//
//        HttpClient httpClient = HttpClients.custom().setConnectionManager(pollingConnectionManager)
//                .evictIdleConnections(30, TimeUnit.SECONDS)
//                // .setRetryHandler(new
//                // DefaultHttpRequestRetryHandler(3, true))
//                // //重试次数，默认是3次，没有开启
//                // .setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE)
//                // //使用请求Keep-Alive的值，没有的话永久有效
//                .setKeepAliveStrategy(new CustomConnectionKeepAliveStrategy()) // 自定义
//                .disableAutomaticRetries().build();
//
//        HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(
//                httpClient);
//        // 连接超时
//        clientHttpRequestFactory.setConnectTimeout(12000);
//        // 数据读取超时时间，即SocketTimeout
//        clientHttpRequestFactory.setReadTimeout(12000);
//        // 连接不够用的等待时间，不宜过长，必须设置，比如连接不够用时，时间过长将是灾难性的
//        clientHttpRequestFactory.setConnectionRequestTimeout(200);
//        // 缓冲请求数据，默认值是true。通过POST或者PUT大量发送数据时，建议将此属性更改为false，以免耗尽内存。
//        // clientHttpRequestFactory.setBufferRequestBody(false);
//
//        restTemplate.setRequestFactory(clientHttpRequestFactory);
        return restTemplate;
    }



    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        return new RestTemplate(factory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);//单位为ms
        factory.setConnectTimeout(5000);//单位为ms
        return factory;
    }


}
